package com.whcoding.multithreading.thredpool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-09-16 16:07
 **/
public class ThreadPoolUtil {

	/**
	 * 创建线程工厂
	 */
	private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();

	/**
	 *
	 * 1、corePoolSize线程池的核心线程数
	 * 2、maximumPoolSize能容纳的最大线程数
	 * 3、keepAliveTime空闲线程存活时间
	 * 4、unit 存活的时间单位
	 * 5、workQueue 存放提交但未执行任务的队列
	 * 6、threadFactory 创建线程的工厂类
	 * 7、handler 等待队列满后的拒绝策略
	 *
	 * new ThreadPoolExecutor.AbortPolicy() // 不执行新任务，直接抛出异常，提示线程池已满
	 * new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里！由调用线程处理该任务
	 * new ThreadPoolExecutor.DiscardPolicy() //不执行新任务，也不抛出异常
	 * new ThreadPoolExecutor.DiscardOldestPolicy() //丢弃队列最前面的任务，然后重新提交被拒绝的任务。
	 *
	 * @param runSize
	 * @return
	 */
	public static ExecutorService createThread(int runSize) {
		//创建线程池
		ThreadPoolExecutor executor = new ThreadPoolExecutor(
				runSize,
				runSize,
				200L,
				TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<>(1024),
				//Executors.defaultThreadFactory(),
				namedThreadFactory,
				new ThreadPoolExecutor.AbortPolicy());
		return executor;
	}
}
